package com.estore.network;

import com.estore.ProductService;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import com.estore.Product;

public class EStoreServer {
    private final ProductService productService=new ProductService();

    public static void main(String[] args) throws Exception{
        EStoreServer server=new EStoreServer();
        ServerSocket serverSocket=new ServerSocket(8888);
        System.out.println("商城服务器已启动监听端口:8888");
        while (true){
            Socket clientSocket=serverSocket.accept();
            System.out.println("接收到客户端连接："+clientSocket.getInetAddress());
            server.handleClient(clientSocket);
        }
    }
    private void handleClient(Socket clientSocket){
        try(ObjectInputStream ois=new ObjectInputStream(clientSocket.getInputStream());
            ObjectOutputStream oos=new ObjectOutputStream(clientSocket.getOutputStream())){
            String request=(String) ois.readObject();
            System.out.println("收到客户端请求："+request);
            Object response=null;
            if("GET_ALL_PRODUCTS".equals(request)){
                List<Product> products=productService.getAllProducts();
                response=products;
                oos.writeObject(response);
                oos.flush();
                System.out.println("已向客户端返回数据");
            }
            if(productService.getProductData().containsKey(request)){
                Product product=productService.findProductById(request);
                response=product;
                oos.writeObject(response);
                oos.flush();
                System.out.println("已向客户端返回数据");
            }
        }catch (Exception e){
            e.getStackTrace();
        }finally {
            try{
                clientSocket.close();;
            }catch (Exception e){
                e.getStackTrace();
            }
        }
    }
}
